package com.smt.common.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 阿里云OSS文件操作
 *
 * @author zhangyi
 * @date 2018年10月3日13:03:58
 */
@Slf4j
@Component
@ConfigurationProperties(prefix = "aliyunoss")
public class AliyunOSSUtil {
    private String endpoint;
    private String keyid;
    private String keysecret;
    private String bucketname;
    private String filehost;
    /**
     *
     *
     * @param is
     * @param file
     * @param cDir 层级子目录
     * @return
     */
    public String upload(InputStream is,File file,String... cDir) {
        log.info("文件上传开始："+file.getName());
        String random = UUID.randomUUID().toString().replace("-","");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        StringBuffer dateStr = new StringBuffer(format.format(new Date()));
        StringBuffer s = new StringBuffer();
        if(cDir != null) {
            Arrays.asList(cDir).stream()
                    .forEach(d -> s.append("/" + d));
        }
                if(null == file && !file.exists()){
            return null;
        }
        s.append("/"+dateStr);
        OSSClient ossClient = new OSSClient(endpoint, keyid, keysecret);
        try {
            FileInputStream fis = (FileInputStream)is;
            //创建上传Object的Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(fis.available());
            metadata.setCacheControl("no-cache");
            metadata.setHeader("Pragma", "no-cache");
            metadata.setContentEncoding("utf-8");
            metadata.setContentType("application/octet-stream");
            metadata.setContentDisposition("filename/filesize=" + file.getName() + "/" + fis.available() + "Byte.");

            //上传文件
            PutObjectResult result = ossClient.putObject(bucketname, (filehost+s+ "/" +
                    random+Constant.FILE_SPILT+ file.getName()), fis,metadata);


            //创建文件路径
            String fileUrl ="http://"+
                    bucketname+"."+
                    endpoint+"/"+
                    filehost +
                    (s + "/" +
                    random+"-"+
                    file.getName());

            //设置权限 这里是公开读
            ossClient.setBucketAcl(bucketname,CannedAccessControlList.PublicRead);
            if(null != result){
                log.info("OSS文件上传成功,文件下载地址："+fileUrl);
                return fileUrl;
            }
        }catch (OSSException oe){
            log.error(oe.getMessage());
        }catch (ClientException ce){
            log.error(ce.getMessage());
        }catch (FileNotFoundException fe){
            log.error(fe.getMessage());
        }catch (IOException ie){
            log.error(ie.getMessage());
        }finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }




    /**
     * 文件下载 TODO
     *
     * @param objectName
     */
    public String download(String objectName){
        OSSClient ossClient = new OSSClient(endpoint, keyid, keysecret);
        try{

        }catch (Exception e){

        }
        log.info("文件下载");
        return null;
    }

    /**
     * 删除文件 TODO
     *
     * @param objectName
     * @return
     */
    public String detele(String objectName){
        log.info("删除文件");
        return null;
    }

    /**
     * 获取文件流
     *
     * @param fileName
     * @return
     */
    public OSSObject getFileStream(String fileName) {
        OSSClient ossClient = new OSSClient(endpoint, keyid, keysecret);
        Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketname, keyid, HttpMethod.GET);
        // 设置过期时间。
        request.setExpiration(expiration);
        // 生成签名URL（HTTP GET请求）。
        URL signedUrl = ossClient.generatePresignedUrl(request);
        // 使用签名URL发送请求。
        Map<String, String> customHeaders = new HashMap<String, String>();
        // 添加GetObject请求头。
        OSSObject object = ossClient.getObject(bucketname,fileName);
        return object;
    }

    public String getEndpoint() {
        return endpoint;
    }

    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }

    public String getKeyid() {
        return keyid;
    }

    public void setKeyid(String keyid) {
        this.keyid = keyid;
    }

    public String getKeysecret() {
        return keysecret;
    }

    public void setKeysecret(String keysecret) {
        this.keysecret = keysecret;
    }

    public String getBucketname() {
        return bucketname;
    }

    public void setBucketname(String bucketname) {
        this.bucketname = bucketname;
    }

    public String getFilehost() {
        return filehost;
    }

    public void setFilehost(String filehost) {
        this.filehost = filehost;
    }
}
